package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.entity.TrainingRecord;
import org.example.demo.entity.User;
import org.example.demo.service.TrainingRecordService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.ReturnMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("training/record")
public class TrainingRecordController {

    @Resource
    private TrainingRecordService trainingRecordService;

    @Resource
    private UserService userService;

    // 分页查询培养记录列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody TrainingRecord trainingRecord,
                                 @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {
//        ReturnMap returnMap = new ReturnMap();
        Page<TrainingRecord> page = new Page<>(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(trainingRecord.getNickName()!=null&&!trainingRecord.getNickName().isEmpty(),User::getName,trainingRecord.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            // 批量查询用户信息
            QueryWrapper<TrainingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(TrainingRecord::getUserId, userMap.keySet())
                    .orderByDesc(TrainingRecord ::getCreateTime);

            Page<TrainingRecord> result = trainingRecordService.page(page, queryWrapper);
            // 遍历结果集，设置用户昵称
            for (TrainingRecord record : result.getRecords()) {
                User user = userMap.get(record.getUserId());
                if (user != null) {
                    record.setNickName(user.getName());
                }
            }

            map.put("page", result);
//            returnMap.setData("page", result);
        }else{
            map.put("page", new ArrayList<>());
//            returnMap.setData("page", new ArrayList<>());
        }

        return AjaxResult.success(map);
    }

    // 查询培养记录详情
    @GetMapping("detail")
    public AjaxResult detail(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        TrainingRecord record = trainingRecordService.getById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("record", record);
//        returnMap.setData("record", record);
//        return returnMap.getreturnMap();
        return AjaxResult.success(map);
    }

    // 新增/修改培养记录
    @PostMapping("saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody TrainingRecord record) {
//        ReturnMap returnMap = new ReturnMap();

        if (record.getId() != null) {
            record.setUpdateTime(LocalDateTime.now());
            trainingRecordService.updateById(record);
        } else {
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            trainingRecordService.save(record);
        }

//        returnMap.setReturnCode(200);
        return AjaxResult.success();
    }

    // 获取申请人培养记录
    @GetMapping("byApplicant")
    public AjaxResult getByApplicant(@RequestParam Integer applicantId,
                                              @RequestParam(defaultValue = "10") Integer limit) {
//        ReturnMap returnMap = new ReturnMap();
        QueryWrapper<TrainingRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(TrainingRecord::getApplicantId, applicantId)
                .orderByDesc(TrainingRecord::getTrainingDate)
                .last("LIMIT " + limit);

//        returnMap.setData("records", trainingRecordService.list(queryWrapper));

        Map<String, Object> map = new HashMap<>();
        map.put("records", trainingRecordService.list(queryWrapper));
        return AjaxResult.success(map);
    }

    // 查询谈话信息总数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody TrainingRecord trainingRecord) {
//        ReturnMap returnMap = new ReturnMap();

        Map<String, Object> map = new HashMap<>();
        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(trainingRecord.getNickName()!=null&&!trainingRecord.getNickName().isEmpty(),User::getName,trainingRecord.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            QueryWrapper<TrainingRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(TrainingRecord::getUserId, userMap.keySet())
                    .eq(trainingRecord.getApplicantId() != null,
                            TrainingRecord::getApplicantId, trainingRecord.getApplicantId());

            int count = trainingRecordService.count(queryWrapper);
//            returnMap.setData("count", count);
            map.put("count", count);
        }else{
            map.put("count", 0);
//            returnMap.setData("count", 0);
        }

        return AjaxResult.success(map);
//        return returnMap.getreturnMap();
    }

    // 删除培养记录
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        boolean success = trainingRecordService.removeById(id);

        if (success) return AjaxResult.success();
        return AjaxResult.error();
//        returnMap.setReturnCode(success ? 200 : 405);
//        return returnMap.getreturnMap();
    }

    // 培养记录统计
    @GetMapping("statistics")
    public AjaxResult getStatistics(@RequestParam Integer applicantId) {
//        ReturnMap returnMap = new ReturnMap();
        // 统计培养次数、最近培养时间等
        return AjaxResult.success();
    }
}
